<template>
  <div class="seat-selector">
    <div class="train-info">
      <h3>{{ train.trainNumber }}次 {{ train.startStationName }} → {{ train.endStationName }}</h3>
      <p>{{ train.travelDate }} {{ train.departureTime }} - {{ train.arrivalTime }}</p>
    </div>

    <div class="carriages-section" v-loading="loading">
      <div v-for="carriage in carriages" :key="carriage.id" class="carriage-card">
        <el-card>
          <template #header>
            <div class="carriage-header">
              <span>{{ carriage.carriageNumber }}号车厢 - {{ getCarriageTypeLabel(carriage.carriageType) }}</span>
              <span class="available-count">可选座位: {{ carriage.availableSeats }}</span>
            </div>
          </template>
          
          <div v-if="getCarriageSeats(carriage.id).length > 0" class="seats-grid">
            <div 
              v-for="seat in getCarriageSeats(carriage.id)" 
              :key="seat.id"
              class="seat-item"
              :class="getSeatClasses(seat)"
              @click="selectSeat(seat)"
              :title="`${seat.seatNumber} - ¥${seat.price}`"
            >
              {{ seat.seatNumber }}
            </div>
          </div>
          
          <div v-else class="no-seats">
            暂无可用座位
          </div>
        </el-card>
      </div>
    </div>

    <div v-if="carriages.length === 0 && !loading" class="no-data">
      暂无车厢信息
    </div>

    <div class="legend">
      <span class="legend-item">
        <span class="seat available"></span>
        可选座位
      </span>
      <span class="legend-item">
        <span class="seat occupied"></span>
        已售
      </span>
      <span class="legend-item">
        <span class="seat window"></span>
        靠窗
      </span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { carriageApi, seatApi } from '@/api/train'
import { CARRIAGE_TYPE_MAP } from '@/constants/train'
import type { Train, Carriage, Seat, CarriageType } from '@/types/train'

const props = defineProps<{
  train: Train
  startStationId: number
  endStationId: number
}>()

const emit = defineEmits<{
  seatSelected: [seat: Seat]
}>()

const loading = ref(false)
const carriages = ref<Carriage[]>([])
const seats = ref<Seat[]>([])

// 获取车厢列表
const fetchCarriages = async () => {
  try {
    loading.value = true
    const response = await carriageApi.getCarriagesByTrainId(props.train.id)
    if (response.success) {
      carriages.value = response.data
      // 获取每个车厢的座位
      await fetchAllSeats()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('获取车厢信息失败:', error)
    ElMessage.error('获取车厢信息失败')
  } finally {
    loading.value = false
  }
}

// 获取所有座位
const fetchAllSeats = async () => {
  try {
    const response = await seatApi.getSeatsByTrainId(props.train.id)
    if (response.success) {
      seats.value = response.data
    }
  } catch (error) {
    console.error('获取座位信息失败:', error)
    ElMessage.error('获取座位信息失败')
  }
}

// 获取指定车厢的座位
const getCarriageSeats = (carriageId: number) => {
  return seats.value
    .filter(seat => seat.carriageId === carriageId)
    .sort((a, b) => {
      // 提取座位号的数字部分和字母部分
      const parseSeateNumber = (seatNumber: string) => {
        const match = seatNumber.match(/^(\d+)([A-Z])$/)
        if (match) {
          return { row: parseInt(match[1]), col: match[2] }
        }
        return { row: 0, col: 'A' }
      }
      
      const seatA = parseSeateNumber(a.seatNumber)
      const seatB = parseSeateNumber(b.seatNumber)
      
      // 先按行数排序，再按列字母排序
      if (seatA.row !== seatB.row) {
        return seatA.row - seatB.row
      }
      return seatA.col.localeCompare(seatB.col)
    })
}

// 选择座位
const selectSeat = (seat: Seat) => {
  if (!seat.isAvailable) {
    ElMessage.warning('该座位已被占用')
    return
  }
  
  emit('seatSelected', seat)
}

// 获取座位CSS类
const getSeatClasses = (seat: Seat) => {
  const classes = ['seat']
  
  if (seat.isAvailable) {
    classes.push('available')
  } else {
    classes.push('occupied')
  }
  
  if (seat.seatType === 'WINDOW') {
    classes.push('window')
  }
  
  return classes
}

// 获取车厢类型标签
const getCarriageTypeLabel = (type: CarriageType) => {
  return CARRIAGE_TYPE_MAP[type] || type
}

onMounted(() => {
  fetchCarriages()
})
</script>

<style scoped>
.seat-selector {
  padding: 20px;
}

.train-info {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.train-info h3 {
  margin: 0 0 10px 0;
  color: #303133;
}

.train-info p {
  margin: 0;
  color: #606266;
}

.carriages-section {
  max-height: 600px;
  overflow-y: auto;
}

.carriage-card {
  margin-bottom: 20px;
}

.carriage-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.available-count {
  color: #67c23a;
  font-weight: bold;
}

.seats-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 8px;
  max-width: 400px;
  margin: 0 auto;
}

.seat-item {
  width: 60px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  font-size: 12px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid transparent;
  user-select: none;
}

.seat.available {
  background-color: #67c23a;
  color: white;
}

.seat.available:hover {
  background-color: #529b2e;
  transform: scale(1.05);
}

.seat.occupied {
  background-color: #f56c6c;
  color: white;
  cursor: not-allowed;
}

.seat.window {
  border-color: #409eff;
}

.no-seats, .no-data {
  text-align: center;
  color: #909399;
  padding: 40px;
}

.legend {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
}

.legend .seat {
  width: 30px;
  height: 20px;
  border-radius: 4px;
  border: 1px solid transparent;
}
</style>